package com.org.manhu.chargehelper.ui;

import java.io.File;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.broadcastreceiver.USBBroadcastReceiver;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateMoneyReceiver;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateNickNameReceiver;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.custom.BatteryCharger;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.DeviceInfo;
import com.org.manhu.chargehelper.tools.FileUtil;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.NetUtils;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.ui.fragment.AppListFragment;
import com.org.manhu.chargehelper.ui.fragment.NetAppListFragment;
import com.org.manhu.chargehelper.update.UpdateManager;
import com.org.manhu.chargehelper.updateutils.UpdateUtil;
import com.org.manhu.chargehelper.webservice.AsyncProcessData;

/**
 * @文件名：HomeActivity.java
 * @包名：com.org.manhu.chargehelper.ui
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月4日 下午2:27:46
 *
 * @描述：
 */
@SuppressLint("HandlerLeak")
public class HomeActivity extends FragmentActivity implements OnClickListener {

	private long mExitTime; // 两次点击的时间间隔
	private static final int CHECK_OFFLINE_RESOURCE = 0x0001;
	private String path = "/mnt/sdcard/manhu/crash/offlineResource.txt";

	private String channelId, devId;

	private RadioGroup tabRg;
	private FragmentManager fm;
	private FragmentTransaction ft;
	private AppListFragment appFragment, gameFragment, xiquFragment,
			ebookFragment;
	private NetAppListFragment netAppFragment, netGameFragment,
			netXiquFragment, netEbookFragment;
	private TextView nickNameTv, awardNumTv;

	// private RelativeLayout userInfoLayout;
	private ImageView backIv, userInfoMoreIv;
	private BatteryCharger battery;
	private Button cashOutBtn, exchangeBtn;
	private USBBroadcastReceiver receiver;
	private UpdateNickNameReceiver mReceiver;
	private UpdateMoneyReceiver receivers;

	private float money;

	private AsyncProcessData request;
	private ProgressDialog mPd;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == CHECK_OFFLINE_RESOURCE) {
				File file = new File(path);
				if (file.exists()) {
					mPd.dismiss();
					mHandler.removeMessages(CHECK_OFFLINE_RESOURCE);
					String json = FileUtil.readFileData(path);
					Map<String, List<Map<String, String>>> data = JsonUtil
							.parseBoxData(json);
					if (data != null) {
						if (appFragment.isAdded()) {
							appFragment.notify(data.get("应用"));
						} else {
							appFragment.setData(data.get("应用"));
						}
						if (gameFragment.isAdded()) {
							gameFragment.notify(data.get("游戏"));
						} else {
							gameFragment.setData(data.get("游戏"));
						}
						if (xiquFragment.isAdded()) {
							xiquFragment.notify(data.get("视频"));
						} else {
							xiquFragment.setData(data.get("视频"));
						}
						if (ebookFragment.isAdded()) {
							ebookFragment.notify(data.get("电子书"));
						} else {
							ebookFragment.setData(data.get("电子书"));
						}
					}
				} else {
					mHandler.sendEmptyMessageDelayed(CHECK_OFFLINE_RESOURCE,
							1000);
				}

			} else if (Constant.CLIENT_INIT.equals(msg.obj.toString())) {
				Log.d("TAG", "初始化：：：" + msg.getData().getString("jsonStr"));
				Map<String, String> map = JsonUtil.parseToMap(msg.getData()
						.getString("jsonStr"));
				if (map != null) {
					ChargeApplication.setInitInfo(map);
					getUserInfo();
				}
			} else if (Constant.GET_USER_INFO.equals(msg.obj.toString())) {
				Log.d("TAG", "用户信息：：：" + msg.getData().getString("jsonStr"));
				Map<String, String> map = JsonUtil.parseToMap(msg.getData()
						.getString("jsonStr"));
				if (map != null) {
					money = Float.parseFloat(map.get("Money"));
					SharedPreferncesUtil.saveMoney(HomeActivity.this, money);
					awardNumTv.setText(money + "");
					nickNameTv.setText(map.get("Assignname"));
					SharedPreferncesUtil.saveNickName(HomeActivity.this,
							map.get("Assignname"));
				}
			} else if (Constant.APP_LIST.equals(msg.obj.toString())) {
				Map<String, List<Map<String, String>>> collection = JsonUtil
						.categoryParse(msg.getData().getString("jsonStr"));
				mPd.dismiss();
				if (collection != null) {
					if (netAppFragment.isAdded()) {
						netAppFragment.notify(collection.get("应用"));
					} else {
						netAppFragment.setData(collection.get("应用"));
					}
					if (netGameFragment.isAdded()) {
						netGameFragment.notify(collection.get("游戏"));
					} else {
						netGameFragment.setData(collection.get("游戏"));
					}
					if (netXiquFragment.isAdded()) {
						netXiquFragment.notify(collection.get("视频"));
					} else {
						netXiquFragment.setData(collection.get("视频"));
					}
					if (netEbookFragment.isAdded()) {
						netEbookFragment.notify(collection.get("电子书"));
					} else {
						netEbookFragment.setData(collection.get("电子书"));
					}
				}
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		AppManager.getAppManager().addActivity(this);

		request = new AsyncProcessData();

		mPd = new ProgressDialog(this);
		mPd.setMessage("正在获取数据，请耐心等待……");
		mPd.setCanceledOnTouchOutside(false);

		tabRg = (RadioGroup) findViewById(R.id.category_tab);
		// userInfoLayout = (RelativeLayout) findViewById(R.id.user_info);
		userInfoMoreIv = (ImageView) findViewById(R.id.user_info_more);
		battery = (BatteryCharger) findViewById(R.id.battery_charge);
		backIv = (ImageView) findViewById(R.id.title_back);
		cashOutBtn = (Button) findViewById(R.id.tixian_btn);
		cashOutBtn.setVisibility(View.GONE);
		exchangeBtn = (Button) findViewById(R.id.exchange_btn);
		nickNameTv = (TextView) findViewById(R.id.user_name);
		backIv.setVisibility(View.GONE);
		awardNumTv = (TextView) findViewById(R.id.user_award_num);
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");

		if (ChargeApplication.isBoxConnected) {
			receiver = new USBBroadcastReceiver();
			// registerReceiver();
			mHandler.sendEmptyMessageDelayed(CHECK_OFFLINE_RESOURCE, 1000);
			mPd.show();

			battery.setVisibility(View.VISIBLE);
			battery.startChargerAnim();
			appFragment = new AppListFragment(Constant.APP_LIST_TYPE_APP);
			gameFragment = new AppListFragment(Constant.APP_LIST_TYPE_GAME);
			ebookFragment = new AppListFragment(Constant.APP_LIST_TYPE_EBOOK);
			xiquFragment = new AppListFragment(Constant.APP_LIST_TYPE_VIDEO);

			fm = getSupportFragmentManager();
			ft = fm.beginTransaction();
			ft.add(R.id.category_tab_fragment, appFragment);
			ft.show(appFragment);
			ft.hide(gameFragment);
			ft.hide(xiquFragment);
			ft.hide(ebookFragment);
			ft.commit();
		} else {
			clientInit();
			request.getRequestData(mHandler, Constant.APP_LIST);
			mPd.show();
			UpdateManager.getInstance().Update(this);
			// UpdateUtil.getInstance().Update(this);

			netAppFragment = new NetAppListFragment();
			netGameFragment = new NetAppListFragment();
			netXiquFragment = new NetAppListFragment();
			netEbookFragment = new NetAppListFragment();

			fm = getSupportFragmentManager();
			ft = fm.beginTransaction();
			ft.add(R.id.category_tab_fragment, netAppFragment);
			ft.show(netAppFragment);
			ft.hide(netGameFragment);
			ft.hide(netXiquFragment);
			ft.hide(netEbookFragment);
			ft.commit();
		}

		tabRg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch (checkedId) {
				case R.id.category_soft_rb:
					ft = fm.beginTransaction();
					if (ChargeApplication.isBoxConnected) {
						gameFragment.onPause();
						xiquFragment.onPause();
						ebookFragment.onPause();
						if (appFragment.isAdded()) {
							appFragment.onResume();
						} else {
							ft.add(R.id.category_tab_fragment, appFragment);
						}
						ft.hide(gameFragment);
						ft.hide(xiquFragment);
						ft.hide(ebookFragment);
						ft.show(appFragment);
					} else {
						netGameFragment.onPause();
						netXiquFragment.onPause();
						netEbookFragment.onPause();
						if (netAppFragment.isAdded()) {
							netAppFragment.onResume();
						} else {
							ft.add(R.id.category_tab_fragment, netAppFragment);
						}
						ft.hide(netGameFragment);
						ft.hide(netXiquFragment);
						ft.hide(netEbookFragment);
						ft.show(netAppFragment);
					}
					ft.commit();
					break;
				case R.id.category_game_rb:
					ft = fm.beginTransaction();
					if (ChargeApplication.isBoxConnected) {
						appFragment.onPause();
						xiquFragment.onPause();
						ebookFragment.onPause();
						if (gameFragment.isAdded()) {
							gameFragment.onResume();
						} else {
							ft.add(R.id.category_tab_fragment, gameFragment);
						}
						ft.hide(appFragment);
						ft.hide(xiquFragment);
						ft.hide(ebookFragment);
						ft.show(gameFragment);
					} else {
						netAppFragment.onPause();
						netXiquFragment.onPause();
						netEbookFragment.onPause();
						if (netGameFragment.isAdded()) {
							netGameFragment.onResume();
						} else {
							ft.add(R.id.category_tab_fragment, netGameFragment);
						}
						ft.hide(netAppFragment);
						ft.hide(netXiquFragment);
						ft.hide(netEbookFragment);
						ft.show(netGameFragment);
					}
					ft.commit();
					break;
				/*
				 * case R.id.category_xiqu_rb: ft = fm.beginTransaction(); if
				 * (ChargeApplication.isBoxConnected) { appFragment.onPause();
				 * gameFragment.onPause(); ebookFragment.onPause(); if
				 * (xiquFragment.isAdded()) { xiquFragment.onResume(); } else {
				 * ft.add(R.id.category_tab_fragment, xiquFragment); }
				 * ft.hide(appFragment); ft.hide(gameFragment);
				 * ft.hide(ebookFragment); ft.show(xiquFragment); } else {
				 * netAppFragment.onPause(); netGameFragment.onPause();
				 * netEbookFragment.onPause(); if (netXiquFragment.isAdded()) {
				 * netXiquFragment.onResume(); } else {
				 * ft.add(R.id.category_tab_fragment, netXiquFragment); }
				 * ft.hide(netAppFragment); ft.hide(netGameFragment);
				 * ft.hide(netEbookFragment); ft.show(netXiquFragment); }
				 * ft.commit(); break;
				 */
				/*
				 * case R.id.category_ebook_rb: ft = fm.beginTransaction(); if
				 * (ChargeApplication.isBoxConnected) { appFragment.onPause();
				 * gameFragment.onPause(); xiquFragment.onPause(); if
				 * (ebookFragment.isAdded()) { ebookFragment.onResume(); } else
				 * { ft.add(R.id.category_tab_fragment, ebookFragment); }
				 * ft.hide(appFragment); ft.hide(gameFragment);
				 * ft.hide(xiquFragment); ft.show(ebookFragment); } else {
				 * netAppFragment.onPause(); netGameFragment.onPause();
				 * netXiquFragment.onPause(); if (netEbookFragment.isAdded()) {
				 * netEbookFragment.onResume(); } else {
				 * ft.add(R.id.category_tab_fragment, netEbookFragment); }
				 * ft.hide(netAppFragment); ft.hide(netGameFragment);
				 * ft.hide(netXiquFragment); ft.show(netEbookFragment); }
				 * ft.commit(); break;
				 */
				}
			}
		});

		setAwardAndNickName();

		// userInfoLayout.setOnClickListener(this);
		userInfoMoreIv.setOnClickListener(this);
		exchangeBtn.setOnClickListener(this);
		cashOutBtn.setOnClickListener(this);
		nickNameTv.setOnClickListener(this);
		mReceiver = new UpdateNickNameReceiver(nickNameTv);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_NICKNAME);
		registerReceiver(mReceiver, filter);

		receivers = new UpdateMoneyReceiver(awardNumTv);
		IntentFilter filters = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_MONEY);
		registerReceiver(receivers, filters);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add("关于");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			startActivity(new Intent(this, AboutActivity.class));
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		setAwardAndNickName();

	}

	/**
	 * @描述：
	 */
	private void setAwardAndNickName() {
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		nickNameTv.setText(SharedPreferncesUtil.getNickName(this));
	}

	/**
	 * @描述：
	 */
	protected void getUserInfo() {
		// TODO Auto-generated method stub
		request.getRequestData(mHandler, Constant.GET_USER_INFO, "AuthKey",
				ChargeApplication.getInitInfo().get("AuthKey"));
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (ChargeApplication.isBoxConnected) {
			// unregisterReceiver(receiver);
		}
		unregisterReceiver(mReceiver);
		unregisterReceiver(receivers);
	}

	public void registerReceiver() {

		IntentFilter filter = new IntentFilter();
		filter.addAction("android.hardware.usb.action.USB_STATE");
		registerReceiver(receiver, filter);
	}

	/**
	 * @描述： 客户端初始化，获取AuthKey
	 */
	private void clientInit() {
		if (Constant.IS_USE_BOXINFO) {
			channelId = SharedPreferncesUtil.getBoxInfo(this,
					Constant.SP_BOX_CHANNELID);
			devId = SharedPreferncesUtil
					.getBoxInfo(this, Constant.SP_BOX_DEVID);
		} else {
			channelId = "0";
			devId = "0";
		}
		request.getRequestData(mHandler, Constant.CLIENT_INIT, "AuthKey", "",
				"Imei", DeviceInfo.getIMEI(), "Imsi", DeviceInfo.getIMSI(),
				"AndroidId", DeviceInfo.getAndroidID(), "PhoneTypeId",
				DeviceInfo.getDeviceModel(), "ChannelId", channelId, "DevId",
				devId);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.user_info_more:
			Intent intent = new Intent(this, CenterActivity.class);
			startActivity(intent);
			break;
		case R.id.tixian_btn:
			Intent it = new Intent(this, CashOutActivity.class);
			startActivity(it);
			break;
		case R.id.exchange_btn:
			Intent its = new Intent(this, ScanActivity.class);
			startActivity(its);
			break;
		case R.id.user_name:
			Intent intent1 = new Intent(this, ModifyNickNameActivity.class);
			intent1.putExtra("nickname", nickNameTv.getText().toString());
			startActivity(intent1);
			break;
		}
	}

	// 返回键的监听
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if ((System.currentTimeMillis() - mExitTime) > 3000) {
				Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();
			} else {
				AppManager.getAppManager().AppExit(getApplicationContext());
			}

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
